package gmomo.test.gui;

import gmomo.packet.Invitation;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class InvitationDialog extends JDialog implements ActionListener {

	private static final long serialVersionUID = -4075195260981721886L;
	private MainFrame main;
	private String to;
	
	private JLabel lblHost;
	private JTextField txtHost;
	private JLabel lblPort;
	private JTextField txtPort;
	private JButton btnSend;
	
	public InvitationDialog (MainFrame main, String to) {
		super(main, "Invitation Dialog", ModalityType.APPLICATION_MODAL);
		this.main = main;
		this.to = to;
		setup();
	}
	
	private void setup() {
		Container contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());
		
		JPanel center = new JPanel( new GridLayout(2,2) );
		JPanel btm = new JPanel();
		
		lblHost = new JLabel("Host: ");
		txtHost = new JTextField("127.0.0.1");
		lblPort = new JLabel("Port: ");
		txtPort = new JTextField("1111");
		center.add(lblHost);
		center.add(txtHost);
		center.add(lblPort);
		center.add(txtPort);
		
		btnSend = new JButton("Send");
		btnSend.addActionListener(this);
		
		btm.add(btnSend);
		contentPane.add( center, BorderLayout.CENTER );
		contentPane.add( btm, BorderLayout.SOUTH );
		
		setPreferredSize( new Dimension( 300, 130 ) );
		setLocation(main.getX(), main.getY());
		pack();
		setVisible(true);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
	}

	public void actionPerformed(ActionEvent e) {
		if ( e.getSource() == btnSend ) {
			Invitation invite = new Invitation(to);
			invite.setBody("Hi i hope to collaborate with you on SharedMind");
			invite.setHost( txtHost.getText() );
			try { 
				invite.setPort( Integer.parseInt(txtPort.getText()) );
			}catch ( NumberFormatException nfe ){ 
				invite.setPort( 1234 );
			}
			main.send(invite.getPacket());
			
			this.setVisible(false);
		}
	}

}//end of class InvitationDialog
